package com.example.api.service;

import com.example.api.entity.Card;
import com.example.api.repository.CardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CardService {
    @Autowired
    private CardRepository cardRepository;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String ALL_CARDS_CACHE_KEY = "cards:all";
    private static final long CACHE_EXPIRATION_TIME = 10; // 缓存过期时间，单位：分钟

    // 获取所有卡片信息
    public List<Card> getAllCards() {
        // 尝试从 Redis 缓存中获取所有卡片数据
        List<Card> cachedCards = (List<Card>) redisTemplate.opsForValue().get(ALL_CARDS_CACHE_KEY);
        if (cachedCards != null) {
            return cachedCards;
        }

        // 如果缓存中没有数据，从数据库中获取
        List<Card> cards = cardRepository.findAll();

        // 将数据存入 Redis 缓存中
        redisTemplate.opsForValue().set(ALL_CARDS_CACHE_KEY, cards, CACHE_EXPIRATION_TIME, TimeUnit.MINUTES);

        return cards;
    }

    // 更新所有卡片信息并刷新缓存
    public void updateAllCards() {
        // 从数据库中获取最新的卡片数据
        List<Card> cards = cardRepository.findAll();

        // 更新 Redis 缓存
        redisTemplate.opsForValue().set(ALL_CARDS_CACHE_KEY, cards, CACHE_EXPIRATION_TIME, TimeUnit.MINUTES);
    }



     public void addCard(Card card) {
        cardRepository.save(card);
        updateAllCards();
     }


    // 删除卡片
    public void deleteCard(int cardId) {
        cardRepository.deleteById(cardId);  // 删除操作根据 cardId 执行
        updateAllCards();
    }

    // 更新卡片
    public void updateCard(Card card) {
        if (card.getCardId() > 0) {
            cardRepository.save(card);  // 更新卡片
            updateAllCards();
        } else {
            throw new IllegalArgumentException("ID无效，更新失败");
        }
    }

    public Card getCardById(int cardId) {
        return cardRepository.findById(cardId).get();
    }
}
